<template>
  <div class="preferences-page">
    <div class="page-header">
      <div class="header-left">
        <el-button 
          type="text" 
          @click="goBackToMain" 
          class="back-btn"
        >
          <el-icon><ArrowLeft /></el-icon>
          {{ $t('common.back') }}
        </el-button>
        <h1>{{ $t('preferences.title') }}</h1>
      </div>
      <div class="header-right">
        <ThemeToggle />
      </div>
    </div>

    <div class="preferences-container" v-loading="loading">
      <!-- 基础设置 -->
      <div class="settings-section">
        <div class="section-header">
          <h2>🌐 {{ $t('preferences.basic.title') }}</h2>
          <p>{{ $t('preferences.basic.subtitle') }}</p>
        </div>
        
        <div class="settings-grid">
          <div class="setting-item">
            <div class="setting-info">
              <h3>{{ $t('preferences.basic.language.title') }}</h3>
              <p>{{ $t('preferences.basic.language.subtitle') }}</p>
            </div>
            <div class="setting-control">
              <el-select 
                v-model="currentLanguage" 
                @change="handleLanguageChange"
                style="width: 200px"
              >
                <el-option 
                  v-for="locale in supportedLocales"
                  :key="locale.value"
                  :label="`${locale.flag} ${locale.label}`"
                  :value="locale.value"
                />
              </el-select>
            </div>
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <h3>{{ $t('preferences.basic.theme.title') }}</h3>
              <p>{{ $t('preferences.basic.theme.subtitle') }}</p>
            </div>
            <div class="setting-control">
              <el-radio-group 
                v-model="currentTheme" 
                @change="handleThemeChange"
                class="theme-radio-group"
              >
                <el-radio-button label="light">
                  <el-icon><Sunny /></el-icon>
                  {{ $t('preferences.basic.theme.light') }}
                </el-radio-button>
                <el-radio-button label="dark">
                  <el-icon><Moon /></el-icon>
                  {{ $t('preferences.basic.theme.dark') }}
                </el-radio-button>
                <el-radio-button label="auto">
                  <el-icon><Monitor /></el-icon>
                  {{ $t('preferences.basic.theme.auto') }}
                </el-radio-button>
              </el-radio-group>
            </div>
          </div>
        </div>
      </div>

      <!-- 语音设置 -->
      <div class="settings-section">
        <div class="section-header">
          <h2>🔊 {{ $t('preferences.voice.title') }}</h2>
          <p>{{ $t('preferences.voice.subtitle') }}</p>
        </div>
        
        <div class="settings-grid">
          <div class="setting-item">
            <div class="setting-info">
              <h3>{{ $t('preferences.voice.enabled.title') }}</h3>
              <p>{{ $t('preferences.voice.enabled.subtitle') }}</p>
            </div>
            <div class="setting-control">
              <el-switch 
                v-model="preferences.voice_enabled" 
                @change="handlePreferenceChange"
                size="large"
              />
            </div>
          </div>

          <div class="setting-item" :class="{ disabled: !preferences.voice_enabled }">
            <div class="setting-info">
              <h3>{{ $t('preferences.voice.speed.title') }}</h3>
              <p>{{ $t('preferences.voice.speed.subtitle') }}</p>
            </div>
            <div class="setting-control">
              <div class="speed-control">
                <el-slider
                  v-model="preferences.voice_speed"
                  :min="0.5"
                  :max="2.0"
                  :step="0.1"
                  :disabled="!preferences.voice_enabled"
                  @change="handlePreferenceChange"
                  style="width: 150px"
                />
                <span class="speed-value">{{ preferences.voice_speed }}x</span>
              </div>
            </div>
          </div>

          <div class="setting-item" :class="{ disabled: !preferences.voice_enabled }">
            <div class="setting-info">
              <h3>{{ $t('preferences.voice.autoPlay.title') }}</h3>
              <p>{{ $t('preferences.voice.autoPlay.subtitle') }}</p>
            </div>
            <div class="setting-control">
              <el-switch 
                v-model="preferences.auto_play_voice" 
                @change="handlePreferenceChange"
                :disabled="!preferences.voice_enabled"
                size="large"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 通知设置 -->
      <div class="settings-section">
        <div class="section-header">
          <h2>🔔 {{ $t('preferences.notification.title') }}</h2>
          <p>{{ $t('preferences.notification.subtitle') }}</p>
        </div>
        
        <div class="settings-grid">
          <div class="setting-item">
            <div class="setting-info">
              <h3>{{ $t('preferences.notification.enabled.title') }}</h3>
              <p>{{ $t('preferences.notification.enabled.subtitle') }}</p>
            </div>
            <div class="setting-control">
              <el-switch 
                v-model="preferences.notification_enabled" 
                @change="handlePreferenceChange"
                size="large"
              />
            </div>
          </div>
        </div>
      </div>


      <!-- 隐私设置 -->
      <div class="settings-section">
        <div class="section-header">
          <h2>🛡️ {{ $t('preferences.privacy.title') }}</h2>
          <p>{{ $t('preferences.privacy.subtitle') }}</p>
        </div>
        
        <div class="settings-grid">
          <div class="setting-item">
            <div class="setting-info">
              <h3>{{ $t('preferences.privacy.analytics.title') }}</h3>
              <p>{{ $t('preferences.privacy.analytics.subtitle') }}</p>
            </div>
            <div class="setting-control">
              <el-switch 
                v-model="privacySettings.analytics_enabled" 
                @change="handlePrivacyChange"
                size="large"
              />
            </div>
          </div>

          <div class="setting-item">
            <div class="setting-info">
              <h3>{{ $t('preferences.privacy.personalization.title') }}</h3>
              <p>{{ $t('preferences.privacy.personalization.subtitle') }}</p>
            </div>
            <div class="setting-control">
              <el-switch 
                v-model="privacySettings.personalization_enabled" 
                @change="handlePrivacyChange"
                size="large"
              />
            </div>
          </div>
        </div>
      </div>

      <!-- 操作按钮 -->
      <div class="actions-section">
        <el-button 
          type="primary" 
          @click="saveAllSettings" 
          :loading="saving"
          size="large"
        >
          {{ $t('preferences.actions.saveAll') }}
        </el-button>
        <el-button 
          @click="resetToDefaults" 
          size="large"
        >
          {{ $t('preferences.actions.resetDefaults') }}
        </el-button>
      </div>
    </div>

    <!-- 收藏小说管理对话框 -->
    <el-dialog
      v-model="showFavoriteNovels"
      title="收藏小说管理"
      width="600px"
    >
      <div class="favorite-list">
        <div v-if="favoriteNovelsList.length === 0" class="empty-state">
          <el-icon><Reading /></el-icon>
          <p>暂无收藏的小说</p>
        </div>
        <div 
          v-for="novel in favoriteNovelsList" 
          :key="novel.id" 
          class="favorite-item"
        >
          <div class="item-info">
            <h4>{{ novel.title }}</h4>
            <p>{{ novel.author }}</p>
          </div>
          <el-button 
            type="text" 
            @click="removeFavoriteNovel(novel.id)"
            class="remove-btn"
          >
            移除
          </el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 收藏角色管理对话框 -->
    <el-dialog
      v-model="showFavoriteCharacters"
      title="收藏角色管理"
      width="600px"
    >
      <div class="favorite-list">
        <div v-if="favoriteCharactersList.length === 0" class="empty-state">
          <el-icon><Avatar /></el-icon>
          <p>暂无收藏的角色</p>
        </div>
        <div 
          v-for="character in favoriteCharactersList" 
          :key="character.id" 
          class="favorite-item"
        >
          <div class="item-info">
            <h4>{{ character.name }}</h4>
            <p>{{ character.novel_title }}</p>
          </div>
          <el-button 
            type="text" 
            @click="removeFavoriteCharacter(character.id)"
            class="remove-btn"
          >
            移除
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, Sunny, Moon, Monitor, Reading, Avatar
} from '@element-plus/icons-vue'
import { userApi } from '../services/userApi'
import type { UserPreference, UserPreferenceUpdate } from '../types/user'
import { setLocale, getCurrentLocale, supportedLocales, type SupportedLocale } from '../i18n'
import { setTheme, getCurrentTheme, type ThemeMode } from '../utils/theme'
import { getRouteHistory } from '../router'
import ThemeToggle from '../components/common/ThemeToggle.vue'

// 路由实例
const router = useRouter()
const { t } = useI18n()

// 响应式数据
const loading = ref(false)
const saving = ref(false)
const showFavoriteNovels = ref(false)
const showFavoriteCharacters = ref(false)

// 语言和主题设置
const currentLanguage = ref<SupportedLocale>(getCurrentLocale())
const currentTheme = ref<ThemeMode>(getCurrentTheme())

// 偏好设置数据
const preferences = reactive<UserPreferenceUpdate>({
  language: 'zh-CN',
  theme: 'light',
  voice_enabled: true,
  voice_speed: 1.0,
  auto_play_voice: true,
  notification_enabled: true,
  favorite_novels: [],
  favorite_characters: [],
  privacy_settings: {}
})

// 隐私设置
const privacySettings = reactive({
  analytics_enabled: true,
  personalization_enabled: true
})

// 收藏列表
const favoriteNovelsList = ref<Array<{ id: number; title: string; author: string }>>([])
const favoriteCharactersList = ref<Array<{ id: number; name: string; novel_title: string }>>([])

// 是否有未保存的更改
const hasUnsavedChanges = ref(false)

// 方法
const loadPreferences = async () => {
  try {
    loading.value = true
    const userPreferences = await userApi.getUserPreferences()
    
    // 获取当前实际的主题设置（优先使用localStorage中的值）
    const currentActualTheme = getCurrentTheme()
    
    // 更新偏好设置
    Object.assign(preferences, {
      language: userPreferences.language || getCurrentLocale(),
      theme: currentActualTheme, // 使用当前实际的主题设置
      voice_enabled: userPreferences.voice_enabled ?? true,
      voice_speed: userPreferences.voice_speed || 1.0,
      auto_play_voice: userPreferences.auto_play_voice ?? true,
      notification_enabled: userPreferences.notification_enabled ?? true,
      favorite_novels: userPreferences.favorite_novels || [],
      favorite_characters: userPreferences.favorite_characters || [],
      privacy_settings: userPreferences.privacy_settings || {}
    })
    
    // 同步当前语言和主题设置
    currentLanguage.value = preferences.language as SupportedLocale
    currentTheme.value = currentActualTheme // 使用当前实际的主题设置
    
    // 更新隐私设置
    const privacyData = userPreferences.privacy_settings || {}
    privacySettings.analytics_enabled = privacyData.analytics_enabled ?? true
    privacySettings.personalization_enabled = privacyData.personalization_enabled ?? true
    
    // 加载收藏列表详情（这里应该调用相应的API获取详细信息）
    await loadFavoriteDetails()
    
  } catch (error) {
    console.error('加载偏好设置失败:', error)
    ElMessage.error(t('preferences.messages.loadFailed'))
    
    // API调用失败时，确保使用当前实际的主题设置
    const currentActualTheme = getCurrentTheme()
    currentTheme.value = currentActualTheme
    preferences.theme = currentActualTheme
    
    // 设置默认语言
    const currentActualLanguage = getCurrentLocale()
    currentLanguage.value = currentActualLanguage
    preferences.language = currentActualLanguage
  } finally {
    loading.value = false
  }
}

const loadFavoriteDetails = async () => {
  // 这里应该调用API获取收藏的小说和角色详细信息
  // 暂时使用模拟数据
  favoriteNovelsList.value = []
  favoriteCharactersList.value = []
}

// 处理语言变化
const handleLanguageChange = (locale: SupportedLocale) => {
  currentLanguage.value = locale
  setLocale(locale)
  hasUnsavedChanges.value = true
  
  // 更新偏好设置中的语言
  preferences.language = locale
  
  ElMessage.success(t('preferences.messages.saveSuccess'))
}

// 处理主题变化
const handleThemeChange = (theme: ThemeMode) => {
  console.log('PreferencesPage: 主题切换:', { from: currentTheme.value, to: theme })
  
  // 立即更新当前主题值
  currentTheme.value = theme
  
  // 应用主题到DOM（这会触发全局theme-changed事件）
  setTheme(theme)
  
  // 更新偏好设置中的主题
  preferences.theme = theme
  hasUnsavedChanges.value = true
  
  // 验证主题是否正确应用
  setTimeout(() => {
    const htmlClass = document.documentElement.classList.contains('dark')
    const storedTheme = localStorage.getItem('echo_role_theme')
    console.log('PreferencesPage: 主题应用验证:', { 
      theme, 
      isDarkClass: htmlClass, 
      storedTheme,
      currentTheme: currentTheme.value 
    })
  }, 100)
  
  // 强制触发页面重新渲染
  setTimeout(() => {
    // 触发一个自定义事件来通知其他组件
    window.dispatchEvent(new CustomEvent('preferences-theme-changed', { 
      detail: { theme } 
    }))
  }, 50)
  
  ElMessage.success(t('preferences.messages.saveSuccess'))
}

const handlePreferenceChange = () => {
  hasUnsavedChanges.value = true
}

const handlePrivacyChange = () => {
  hasUnsavedChanges.value = true
  preferences.privacy_settings = {
    ...preferences.privacy_settings,
    analytics_enabled: privacySettings.analytics_enabled,
    personalization_enabled: privacySettings.personalization_enabled
  }
}

// 移除重复的主题处理函数，使用utils/theme.ts中的setTheme函数

const saveAllSettings = async () => {
  try {
    saving.value = true
    
    // 更新隐私设置到preferences中
    preferences.privacy_settings = {
      analytics_enabled: privacySettings.analytics_enabled,
      personalization_enabled: privacySettings.personalization_enabled
    }
    
    await userApi.updateUserPreferences(preferences)
    hasUnsavedChanges.value = false
    ElMessage.success(t('preferences.messages.saveSuccess'))
    
  } catch (error) {
    console.error('保存设置失败:', error)
    ElMessage.error(t('preferences.messages.saveFailed'))
  } finally {
    saving.value = false
  }
}

const resetToDefaults = async () => {
  try {
    await ElMessageBox.confirm(t('preferences.messages.resetConfirm'), t('common.warning'), {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning'
    })
    
    // 重置为默认值
    Object.assign(preferences, {
      language: 'zh-CN',
      theme: 'light',
      voice_enabled: true,
      voice_speed: 1.0,
      auto_play_voice: true,
      notification_enabled: true,
      privacy_settings: {
        analytics_enabled: true,
        personalization_enabled: true
      }
    })
    
    privacySettings.analytics_enabled = true
    privacySettings.personalization_enabled = true
    
    hasUnsavedChanges.value = true
    setTheme('light')
    currentTheme.value = 'light'
    
    ElMessage.success(t('preferences.messages.resetSuccess'))
    
  } catch (error) {
    // 用户取消操作
  }
}

const removeFavoriteNovel = async (novelId: number) => {
  try {
    await userApi.removeFavoriteNovel(novelId)
    
    // 更新本地数据
    if (preferences.favorite_novels) {
      const index = preferences.favorite_novels.indexOf(novelId)
      if (index > -1) {
        preferences.favorite_novels.splice(index, 1)
      }
    }
    
    favoriteNovelsList.value = favoriteNovelsList.value.filter(novel => novel.id !== novelId)
    ElMessage.success('已移除收藏')
    
  } catch (error) {
    console.error('移除收藏失败:', error)
    ElMessage.error('移除收藏失败')
  }
}

const removeFavoriteCharacter = async (characterId: number) => {
  try {
    await userApi.removeFavoriteCharacter(characterId)
    
    // 更新本地数据
    if (preferences.favorite_characters) {
      const index = preferences.favorite_characters.indexOf(characterId)
      if (index > -1) {
        preferences.favorite_characters.splice(index, 1)
      }
    }
    
    favoriteCharactersList.value = favoriteCharactersList.value.filter(char => char.id !== characterId)
    ElMessage.success('已移除收藏')
    
  } catch (error) {
    console.error('移除收藏失败:', error)
    ElMessage.error('移除收藏失败')
  }
}

// 页面离开前检查未保存的更改
const checkUnsavedChanges = () => {
  if (hasUnsavedChanges.value) {
    return '您有未保存的更改，确定要离开吗？'
  }
}

// 生命周期
onMounted(() => {
  // 初始化当前设置
  currentLanguage.value = getCurrentLocale()
  currentTheme.value = getCurrentTheme()
  
  // 调试信息
  console.log('PreferencesPage mounted:', {
    currentTheme: currentTheme.value,
    htmlHasDarkClass: document.documentElement.classList.contains('dark'),
    localStorage: localStorage.getItem('echo_role_theme')
  })
  
  loadPreferences()
  
  // 监听页面离开
  window.addEventListener('beforeunload', checkUnsavedChanges)
})

// 智能返回到上一个有效页面
const goBackToMain = () => {
  // 确保主题状态在跳转时保持一致
  const currentActualTheme = getCurrentTheme()
  console.log('偏好设置页面: 返回主页面，当前主题:', currentActualTheme)
  
  // 智能返回逻辑
  const history = getRouteHistory()
  const validRoutes = history.filter(route => 
    !['/login', '/register', '/404', '/'].includes(route) &&
    !route.includes('error')
  )
  
  if (validRoutes.length > 0) {
    const lastRoute = validRoutes[validRoutes.length - 1]
    
    // 如果返回的是/main页面，需要恢复Main页面的状态
    if (lastRoute === '/main') {
      // 检查是否有保存的Main页面状态
      const savedState = localStorage.getItem('mainPageState')
      if (savedState) {
        // 有保存的状态，直接跳转到/main，状态会在Main.vue中恢复
        router.push('/main')
        return
      }
    }
    
    // 返回到最后一个有效页面
    router.push(lastRoute)
  } else {
    // 没有有效历史，返回主页面
    router.push('/main')
  }
}

// 清理
const cleanup = () => {
  window.removeEventListener('beforeunload', checkUnsavedChanges)
}
</script>

<style scoped>
.preferences-page {
  min-height: 100vh;
  background: var(--background);
  padding: 20px;
  transition: background-color 0.3s ease;
}

.page-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-btn {
  color: var(--primary-color);
  font-weight: 500;
}

.page-header h1 {
  font-size: 24px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0;
}

.preferences-container {
  max-width: 900px;
  margin: 0 auto;
}

.settings-section {
  background: var(--surface);
  border-radius: 16px;
  padding: 24px;
  margin-bottom: 24px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  transition: background-color 0.3s ease;
}

.section-header {
  margin-bottom: 24px;
}

.section-header h2 {
  font-size: 20px;
  font-weight: 700;
  color: var(--text-primary);
  margin-bottom: 8px;
}

.section-header p {
  color: var(--text-secondary);
  margin: 0;
}

.settings-grid {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.setting-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  border-radius: 12px;
  border: 2px solid var(--border);
  transition: all 0.2s ease;
  background: var(--surface);
}

.setting-item:hover {
  border-color: var(--primary-color);
  background: var(--background);
}

.setting-item.disabled {
  opacity: 0.6;
  pointer-events: none;
}

.setting-info {
  flex: 1;
}

.setting-info h3 {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.setting-info p {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

.setting-control {
  flex-shrink: 0;
}

.theme-radio-group :deep(.el-radio-button__inner) {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
}

.speed-control {
  display: flex;
  align-items: center;
  gap: 12px;
}

.speed-value {
  font-weight: 600;
  color: #667eea;
  min-width: 40px;
}

.favorites-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  border-radius: 12px;
  border: 2px solid #f3f4f6;
  transition: all 0.2s ease;
}

.stat-card:hover {
  border-color: #667eea;
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.15);
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  color: white;
}

.stat-icon.novels {
  background: linear-gradient(135deg, #667eea, #764ba2);
}

.stat-icon.characters {
  background: linear-gradient(135deg, #f093fb, #f5576c);
}

.stat-info {
  flex: 1;
}

.stat-info h3 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.stat-number {
  font-size: 24px;
  font-weight: 700;
  color: #667eea;
}

.actions-section {
  display: flex;
  gap: 16px;
  justify-content: center;
  padding: 24px;
}

.favorite-list {
  max-height: 400px;
  overflow-y: auto;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #6b7280;
}

.empty-state .el-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.favorite-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f3f4f6;
}

.favorite-item:last-child {
  border-bottom: none;
}

.item-info h4 {
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 4px;
}

.item-info p {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

.remove-btn {
  color: #ef4444;
}

.remove-btn:hover {
  color: #dc2626;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .preferences-page {
    padding: 16px;
  }
  
  .setting-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .setting-control {
    width: 100%;
  }
  
  .actions-section {
    flex-direction: column;
    align-items: stretch;
  }
  
  .favorites-stats {
    grid-template-columns: 1fr;
  }
}

/* 深色主题特殊样式 */
:global(.dark) .preferences-page {
  background: var(--background);
}

:global(.dark) .settings-section {
  background: var(--surface);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
}

:global(.dark) .setting-item {
  background: var(--surface);
  border-color: var(--border);
}

:global(.dark) .setting-item:hover {
  background: var(--background);
  border-color: var(--primary-color);
}

:global(.dark) .theme-radio-group .el-radio-button__inner {
  background-color: var(--surface);
  border-color: var(--border);
  color: var(--text-primary);
}

:global(.dark) .theme-radio-group .el-radio-button__inner:hover {
  background-color: var(--background);
  color: var(--primary-color);
}

:global(.dark) .theme-radio-group .el-radio-button.is-active .el-radio-button__inner {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
  color: white;
}
</style> 